// https://blog.csdn.net/qq_35014708/article/details/88951415
const logger = require('./logger')
const { MySQL } = require('./Mysqldb')
const { PostgreSQL } = require('./Postgredb')

class Query {
  static getOracleData (info, query) {
    return new Promise(function (resolve, reject) {
      Oracle.connect(info).then((oracleConfig) => {
        oracleConfig.execute(
          query,
          [],
          { resultSet: true },
          function (err, result) {
            if (err) console.log(err.message)
            result.resultSet.getRows(1000000, function (err, row) {
              if (err) {
                logger.error(`query`, `getOracleData`, `error`, queryErr)
                Oracle.close(mysqlConfig)
              }
              Oracle.close(mysqlConfig)
              resolve(row)
            })
          }
        )
      })
    }).catch((err) => {
      logger.error(`query`, `getMySQLData`, `error`, err)
      reject(err)
    })
  }
  static getMySQLData (info, code) {
    return new Promise(function (resolve, reject) {
      MySQL.connect(info)
        .then(async (mysqlConfig) => {
          mysqlConfig.query(code, function (queryErr, rows) {
            if (queryErr) {
              logger.error(`query`, `getMySQLData`, `error`, queryErr)
              MySQL.close(mysqlConfig)
              reject(queryErr)
            }
            MySQL.close(mysqlConfig)
            resolve(rows)
          })
        })
        .catch((err) => {
          logger.error(`query`, `getMySQLData`, `error`, err)
          reject(err)
        })
    })
  }
  static getPostgreSQLData (info, code) {
    return new Promise(function (resolve, reject) {
      PostgreSQL.connect(info)
        .then((psqlConfig) => {
          psqlConfig.query(code, [], function (err, response) {
            try {
              if (err) {
                logger.error(
                  `DataSourceController`,
                  `dataSourceCheck`,
                  `error`,
                  err
                )
                PostgreSQL.close(psqlConfig)
                reject(err)
              }
              PostgreSQL.close(psqlConfig)
              logger.error(
                `DataSourceController`,
                `dataSourceCheck`,
                response.rows
              )
              resolve(response.rows)
            } catch (err) {
              logger.error(`query`, `getPostgreSQLData`, `error`, err)
              reject(err)
            }
          })
        })
        .catch((err) => {
          logger.error(`query`, `getPostgreSQLData`, `error`, err)
          reject(err)
        })
    })
  }
}
module.exports = {
  Query,
}
